import { reqUpdateCheckedById, reqDeleteCartById, reqCartList } from '@/api'
const state = {
  cartInfoList: [],
}
const mutations = {
  GETCARTLIST(state, cartInfoList) {
    state.cartInfoList = cartInfoList
  },
}
const actions = {
  async getCartList({ commit }) {
    let result = await reqCartList()

    if (result.code == 200) {
      commit('GETCARTLIST', result.data)
    }
  },
  async deleteCartListBySkuId({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      return result.message
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async UpdateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    } else {
       return Promise.reject(new Error('faile'))
    }
  },
  deleteAllCheckedCart({ dispatch, getters }) {
    // context的话就相当于state的父亲，上一级，包含着state中的所有属性
    //{dispatch,getters}从context中解构！！！！！
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach((item) => {
      if (item.isChecked == 1) {
        let promise = dispatch('deleteCartListBySkuId', item.skuId)
        PromiseAll.push(promise)
      }
    })
    return Promise.all(PromiseAll)
  },
  updateAllCartIsChecked({ dispatch, getters }, isChecked) {
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach((item) => {
      let promise = dispatch('UpdateCheckedById', { skuId: item.skuId, isChecked })
      PromiseAll.push(promise)
    })
    return Promise.all(PromiseAll)
  },
}
const getters = {
  cartList(state) {
    return state.cartInfoList[0] || []
  },
}
export default {
  state,
  actions,
  mutations,
  getters,
}
